import re
from rest_framework_jwt.utils import jwt_payload_handler
from django.contrib.auth.backends import ModelBackend
from users.models import User


def jwt_response_payload_handler(token, user=None, request=None):
    """
    指定JWT返回数据的格式
    :param token:
    :param user: 用户对象
    :param request: 请求提
    :return:
    """
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username
    }


def my_jwt_payload_handler(user):
    # 继承默认载荷的内容,载荷是个字典，可看源码
    payload = jwt_payload_handler(user)
    # 删除默认的邮箱,添加手机号
    del payload['email']
    payload['mobile'] = user.mobile

    return payload


def get_user_by_account(account):
    """
    通过账号获取用户对象
    :param account: 账号，可以是用户名或者手机号
    :return: User对象或者None
    """
    # 这个方式有漏洞，当用户名是一个长的像手机号(和注册的手机号不一样)的时候
    # try:
    #     if re.match(r'1[3-9]\d{9}', account):
    #         user = User.objects.get(mobile=account)
    #     else:
    #         user = User.objects.get(username=account)
    # except User.DoesNotExist:
    #     return None
    #
    # return user

    # 下面这个方式不行，因为如果输入的是手机号，get查不到就直接抛出异常
    # try:
    #     user = User.objects.get(username=account)
    #     if not user:
    #         user = User.objects.get(mobile=account)
    #     return user
    # except User.DoesNotExist:
    #     return None
    try:
        users = User.objects.filter(username=account)
        if users:
            user = users[0]
        else:
            user = User.objects.get(mobile=account)

    except User.DoesNotExist:
        return None

    return user


class Myauthentizationbackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_user_by_account(username)

        if user is not None and user.check_password(password):
            return user








